package com.laiyima.zhongjiang.linghuilv.demo;

import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.laiyima.zhongjiang.linghuilv.demo.Become.BecomeanagentActivity;
import com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider.ServiceproviderActivity;
import com.laiyima.zhongjiang.linghuilv.demo.home.HomeActivity;
import com.laiyima.zhongjiang.linghuilv.demo.me.UserActivity;
import com.laiyima.zhongjiang.linghuilv.demo.shop.ShoppingActivity;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    List<Intent> intentList;
    LocalActivityManager activityManager;
    private String TAG="MainActivity";
    String[] tabIds={"首页","服务商","商城","我的"};
    private String role;
    private RadioGroup radioGroup;
    private ViewPager viewpager;
    private RadioButton rb_home,rb_fw,rb_wode,me_SC;
    private static final int TIME_EXIT=3000;
    private static int isExit=0;


    //实现按两次后退才退出
    private CountDownTimer mCountDownTimer = new CountDownTimer(TIME_EXIT,1000) {
        @Override
        public void onTick(long l) {
            isExit++;
        }

        @Override
        public void onFinish() {
            isExit=0;
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            exit();
            return false;
        }
        return super.onKeyDown(keyCode,event);
    }
    private void exit(){
        if(isExit<1){
            Toast.makeText(getApplicationContext(),"再点击一次返回退出程序",Toast.LENGTH_SHORT).show();
            mCountDownTimer.start();
        }else{
            isExit=0;
            Toast.makeText(getApplicationContext(),"退出程序",Toast.LENGTH_SHORT).show();
            mCountDownTimer.cancel();
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
            System.exit(0);
        }
    }

    public static void start(Context context) {
        start(context, null);
    }
    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }
    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences1 = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences1.getString("userID", "");
        if(userID.equals("")){
            Intent Nameintent = new Intent(MainActivity.this, FirstActivity.class);
            startActivity(Nameintent);
        }

        setContentView(R.layout.activity_main);
        rb_home=findViewById(R.id.main_home_RB);
        Drawable drawable = getResources().getDrawable(R.drawable.radio_home);
        drawable.setBounds(0, 0, 80, 70);
        rb_home.setCompoundDrawables(null, drawable, null, null);

        rb_fw=findViewById(R.id.dynamic_RB);
        Drawable drawable2 = getResources().getDrawable(R.drawable.radio_fuwu);
        drawable2.setBounds(0, 0, 70, 70);
        rb_fw.setCompoundDrawables(null, drawable2, null, null);
        rb_wode=findViewById(R.id.me_RB);
        Drawable drawable1 = getResources().getDrawable(R.drawable.radio_wode);
        drawable1.setBounds(0, 0, 60, 70);
        rb_wode.setCompoundDrawables(null, drawable1, null, null);

        me_SC=findViewById(R.id.me_SC);
        Drawable drawable3 = getResources().getDrawable(R.drawable.radio_shangc);
        drawable3.setBounds(0, 0, 60, 70);
        me_SC.setCompoundDrawables(null, drawable3, null, null);


        //activity页
        activityManager=new LocalActivityManager(this,true);
    //    activityManager.dispatchCreate(savedInstanceState);
        setStatusBar();
        intentList=new LinkedList<Intent>();
        Intent homeIntent=new Intent(this, HomeActivity.class);
        intentList.add(homeIntent);




        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
          role = sharedPreferences.getString("role", "");
        if(role.equals("4")){
            rb_fw.setText("成为服务商");
            Intent recordIntent=new Intent(this, BecomeanagentActivity.class);
            intentList.add(recordIntent);
        }else{
            Intent recordIntent=new Intent(this, ServiceproviderActivity.class);
            intentList.add(recordIntent);
        }

        Intent shoppingIntent=new Intent(this, ShoppingActivity.class);
        intentList.add(shoppingIntent);



        Intent profileIntent=new Intent(this, UserActivity.class);
        intentList.add(profileIntent);




        //设置radioGroup
        radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkedId) {
                // TODO 自动生成的方法存根
                switch (checkedId) {
                    case R.id.main_home_RB:
                        viewpager.setCurrentItem(0);
                        rb_home.setTextColor(Color.parseColor("#126AE4"));
                        rb_fw.setTextColor(Color.parseColor("#8E8E93"));
                        rb_wode.setTextColor(Color.parseColor("#8E8E93"));
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        me_SC.setTextColor(Color.BLACK);
                        break;
                    case R.id.dynamic_RB:
                        viewpager.setCurrentItem(1);
                        rb_fw.setTextColor(Color.parseColor("#126AE4"));
                        rb_wode.setTextColor(Color.parseColor("#8E8E93"));
                        rb_home.setTextColor(Color.parseColor("#8E8E93"));

                        if(role.equals("4")){
                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        }else{
                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                        }

                        me_SC.setTextColor(Color.BLACK);
                        break;
                    case R.id.me_SC:
                        viewpager.setCurrentItem(2);
                        me_SC.setTextColor(Color.parseColor("#126AE4"));
                        rb_home.setTextColor(Color.parseColor("#8E8E93"));
                        rb_fw.setTextColor(Color.parseColor("#8E8E93"));
                        rb_wode.setTextColor(Color.parseColor("#8E8E93"));
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        break;
                    case R.id.me_RB:
                        viewpager.setCurrentItem(3);
                        rb_wode.setTextColor(Color.parseColor("#126AE4"));
                        rb_home.setTextColor(Color.parseColor("#8E8E93"));
                        rb_fw.setTextColor(Color.parseColor("#8E8E93"));
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        me_SC.setTextColor(Color.BLACK);
                        break;

                }
            }

        });

        //设置viewpager
        viewpager=(ViewPager)findViewById(R.id.my_ViewPager);
        viewpager.setAdapter(new MyPageAdapter());
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){

            @Override
            public void onPageScrollStateChanged(int position) {
                // TODO 自动生成的方法存根

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO 自动生成的方法存根

            }

            @Override
            public void onPageSelected(int position) {
                // TODO 自动生成的方法存根
                switch(position){
                    case 0:
                        radioGroup.check(R.id.main_home_RB);
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        break;
                    case 1:
                        radioGroup.check(R.id.dynamic_RB);
                        if(role.equals("4")){
                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        }else{
                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                        }
                        break;

                    case 2:
                        radioGroup.check(R.id.me_SC);

                        break;

                    case 3:
                        radioGroup.check(R.id.me_RB);
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        break;
                 }
            }

        });
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

    }

    protected void onResume(){
        super.onResume();
        activityManager.dispatchResume();
    }

    protected void onPause(){
        super.onPause();
        activityManager.dispatchPause(isFinishing());
    }

    protected void onStop(){
        super.onStop();
        activityManager.dispatchStop();
    }

    protected void onDestory(){
        super.onDestroy();
        activityManager.dispatchDestroy(isFinishing());
    }

    private class MyPageAdapter extends PagerAdapter {

        //临时保存view
        HashMap<String, View> idViewMap;

        public MyPageAdapter(){
            idViewMap=new HashMap<String,View>();
        }

        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return POSITION_NONE;
        }

        @Override
        public void destroyItem(View view, int position, Object arg2) {
            ViewPager viewPager = ((ViewPager) view);
            View tabView=idViewMap.get(tabIds[position]);
            viewPager.removeView(tabView);//移除viewPager中的view

            activityManager.destroyActivity(tabIds[position], true);//销毁activity
            idViewMap.remove(tabIds[position]);//移除idViewMap中的引用
        }

        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return intentList.size();
        }

        @Override
        public Object instantiateItem(View view, int position) {
            ViewPager viewPager = ((ViewPager) view);

            View tabView=idViewMap.get(tabIds[position]);//先向idViewMap获取，看有没有
            if(tabView==null){//没有就新创建一个
                tabView=activityManager.startActivity(tabIds[position], intentList.get(position)).getDecorView();
                idViewMap.put(tabIds[position], tabView);
            }else{//检查是否已加入到某个parent view中
                ViewGroup tabViewParent = (ViewGroup) tabView.getParent();
                if (tabViewParent != null) {
                    tabViewParent.removeAllViewsInLayout();
                }
            }
            viewPager.addView(tabView);

            return tabView;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }

    }
}
